import { RouteRecordRaw } from 'vue-router'
import { IbreadcrumbType } from '@/base-ui/breadcrumb'
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  //1.先加载所有的routes
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((keys) => {
    const route = require('../router/main' + keys.split('.')[1])
    allRoutes.push(route.default)
  })

  //2.根据userMenus判断需要添加的routes
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((item) => {
          return item.path === menu.url
        })
        if (route) {
          routes.push(route)
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(userMenus)

  return routes
}

export function pathMapBreadCrumbs(
  userMenus: any[],
  path: string,
  breadcrumbInfo?: IbreadcrumbType[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapBreadCrumbs(menu.children ?? [], path)
      if (findMenu) {
        breadcrumbInfo?.push(menu)
        breadcrumbInfo?.push(findMenu)
        return breadcrumbInfo
      }
    } else if (menu.type === 2 && menu.url === path) {
      return menu
    }
  }
}
